<template>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
        <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
            @onCreated="handleCreated" />
    </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Boot } from '@wangeditor/editor';
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

function withEmptyHtml(editor) {
    const { getHtml } = editor
    const newEditor = editor

    newEditor.getHtml = () => {
        if (newEditor.isEmpty()) {
            return ''
        }
        return getHtml()
    }

    return newEditor
}
// 注册插件
Boot.registerPlugin(withEmptyHtml);

let props = defineProps({
    modelValue: {
        type: String,
        default(rawProps) {
            return ''
        }
    },
    mode: {
        type: String,
        default(rawProps) {
            return ''
        }
    }
})

// 编辑器实例，必须用 shallowRef
let editorRef = shallowRef();
let toolbarConfig = ref({});
let editorConfig = ref({
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            server: 'http://localhost:3001/upload/editor/',
            fieldName: 'file',
            headers: { Authorization: `Bearer ${sessionStorage.access_token}` },
        }
    }
});
// 内容 HTML
let valueHtml = ref('<p></p>');
let emit = defineEmits(['update:modelValue']);

// 模拟 ajax 异步获取内容
onMounted(() => {
        setTimeout(() => {
            valueHtml.value = props.modelValue
            emit('update:modelValue',valueHtml);
        }, 1500)
    })
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
</script>  